import { _decorator, Component, instantiate, isValid, Node, Prefab, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('resBallUI')
export class resBallUI extends Component {
    @property([Prefab]) 
    numberPrefabList: Prefab[] = [];
    numberNodeList:Node[]=[];

    onLoad() {
        this.node.active = false;
    }

    start() {
    }

    protected onDestroy(): void {
        if(this.numberNodeList.length > 0)
        {
            for (let index = 0; index < this.numberNodeList.length; index++) {
                const element = this.numberNodeList[index];
                if(element && isValid(element))
                {
                    this.node.removeChild(element);
                    element.destroy();
                }
            }
            this.numberNodeList = [];
        }
    }

    updateUI(count:number)
    {
        this.onDestroy();
        
        const textNode = this.node.getChildByName("resBallText");
        if(textNode == null)
        {
            console.error("resBallUI can not get resBallText Node");
            return;
        }

        let scoreString = count.toString();
        const LevelChars = Array.from(scoreString, Number); // 分割为单个字符

        let lastPosX = 0;
        for (let index = 0; index < LevelChars.length; index++) {
            const char = LevelChars[index];
            const imageNode = this.numberPrefabList[char];
            
            if (!imageNode) {
                console.error(`Prefab for digit ${char} is missing`);
                continue;
            }
    
            const ScoreImg = instantiate(imageNode);
    
            // 设置初始属性
            const Transform = ScoreImg.getComponent(UITransform);
            Transform.width = 45;
            Transform.height = 53;
            
            let posX = 0;
            if(index <= 0)
            {
                // 计算位置
                posX = textNode.position.x + 180;
            }
            else
            {
                // 计算位置
                posX = lastPosX + 24*(index+1);
            }
            
            lastPosX = posX;
            ScoreImg.setPosition(posX, 0, 0);
            
            this.node.addChild(ScoreImg);
            this.numberNodeList.push(ScoreImg);
        }
    }
}


